package com.Pan;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author lipanJia
 * @date 2021-11-22 18:16
 */
@SpringBootTest
public class FileResponse {

    // kylin服务器地址  82.157.13.183    82.157.13.62
    private final static String KYLIN_SUBMIT = "http://82.157.13.183:9301/imageLibrary/uploadExcel";

    /**
     * Kylin查重文件发送
     *
     * @throws JSONException
     * @throws InterruptedException
     */
    @Test
    void contextLoadBase() throws JSONException, InterruptedException, IOException {
        // 取图片
        File file = new File("D:\\桌面\\涛哥\\查重历史照片\\查重历史照片\\2021年活动照片\\包含603新品活动的照片");
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            File file1 = files[i];
            String name = file1.getName();
            FileInputStream in = new FileInputStream(file1);
            MultipartFile multipartFile = inputStreamToMultipartFile(in, name);
            String s = doPostFormData(KYLIN_SUBMIT, name, multipartFile);
            System.out.println(s);
            if ("200".equals(JSONObject.parseObject(s).get("code"))) {
                boolean delete = file1.delete();
                if (delete) {
                    System.out.println(file1 + "提交成功，已删除");
                }
            }
            Thread.sleep(1000);
        }
    }

    /**
     * 以post方式调用第三方接口,以form-data 形式  发送 MultipartFile 文件数据
     *
     * @param url           post请求url
     * @param fileParamName 文件参数名称
     * @param multipartFile 文件
     */
    public static String doPostFormData(String url, String fileParamName, MultipartFile multipartFile) {
        // 创建Http实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建HttpPost实例
        HttpPost httpPost = new HttpPost(url);
        // 请求参数配置
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
                .setConnectionRequestTimeout(10000).build();
        httpPost.setConfig(requestConfig);
        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(StandardCharsets.UTF_8);
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            String fileName = multipartFile.getOriginalFilename();
            // 文件流
            builder.addBinaryBody("file", multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
            //表单中其他参数，如果没有其他参数可以注释该部分
//            for(Map.Entry<String, String> entry: paramMap.entrySet()) {
//                builder.addPart(entry.getKey(),new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
//            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            // 执行提交
            CloseableHttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回
                String res = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                return res;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * inputstream 转 MultipartFile
     *
     * @param inputStream
     * @param fileName
     * @return
     */
    public static MultipartFile inputStreamToMultipartFile(InputStream inputStream, String fileName) {

        DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file", MediaType.ALL_VALUE, true, fileName);
        OutputStream os = null;

        try {
            os = fileItem.getOutputStream();
            IOUtils.copy(inputStream, os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert os != null;
                os.close();
                assert inputStream != null;
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return new CommonsMultipartFile(fileItem);
    }


}
